<?php


namespace App\Http\Controllers\Admin;


use App\Http\Common\BaseController;
use App\Models\AdminFunctions;
use App\Models\Notice;
use App\Models\Semester;
use App\Models\SetSemester;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SystemctlController extends BaseController
{

    /**
     * 添加功能
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function creatAdminFunction(Request $request){
        $admin_id = $request->userId;
        $key = $request->input('key',0);
        $icon = $request->input('icon');
        $url = $request->input('url');
        $name = $request->input('name');
        $role_id = $request->input('role_id');

        if (!$key == 0){
            $newKey =  AdminFunctions::where('subkey' ,'=', $key)->withTrashed()->orderby('key','desc')->pluck('key')[0] +1 ;
            $subkey = $key;
        }else {
            $key =  0;
            $newKey =  AdminFunctions::where('subkey' ,'=', $key)->withTrashed()->orderby('key','desc')->pluck('key')[0] +100;
            $subkey = $key;
        }

        //创建启动事务
        DB::beginTransaction();
        try {
            foreach ($role_id as $key){
                AdminFunctions::insert([
                    'role_id' => $key,
                    'subkey' => $subkey,
                    'key' => $newKey,
                    'icon' => $icon,
                    'url' => $url,
                    'name' => $name,
                ]);

            }
            $content = $this->mkNoticeContent($admin_id, '',$name . "功能" ,2);
            $this->creatNotice(7,$admin_id,$content,true);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::ERROR,'失败' );
        }
        return $this->returnJson(self::SUCCESS,'成功' );

    }

    /**
     * 删除功能
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function delAdminFunction(Request $request){
        $admin_id = $request->userId;
        $id = $request->input('id');
        DB::beginTransaction();
        try {

            $name = AdminFunctions::where('id','=',$id)->pluck('name')[0];
            AdminFunctions::where('id','=',$id)->delete();


            $content = $this->mkNoticeContent($admin_id, '',$name . "功能" ,3);
            $this->creatNotice(7,$admin_id,$content,true);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->returnJson(self::ERROR,'失败' ,$e);
        }
        return $this->returnJson(self::SUCCESS,'成功' );
    }
    /**
     * get所有功能
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getAdminFunction(Request $request){
        $admin_id = $request->userId;
        $userRole = $this->getUserRole($admin_id);

        $keys = AdminFunctions::where('role_id','=',$userRole)->where('subkey','=',0)->get();

        foreach ($keys as $key){
            $subkeys = AdminFunctions::where('role_id','=',$userRole)->where('subkey','=',$key['key'])->get();
            $key['subfunctions']  = $subkeys;
        }

        return $this->returnJson(self::SUCCESS,'成功',$keys);
    }

    /**
     * get通知分类
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getFunctionClass(Request $request){
        return $this->returnJson(self::SUCCESS,'成功',AdminFunctions::where('role_id','=',1)->where('subkey','=',0)->get(['id as value','name as label']));
    }

    /**
     * get所有通知
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getNotice(Request $request)
    {
        $admin_id = $request->userId;
        $user_id = $request->get('user_id');
        $function_key = $request->get('function_key');
        $page = $request->input('page',1);

        $pageNum  = ($page-1) * 20;

        $where_array=array();
        if (isset($user_id))$where_array['relation_user_id'] = $user_id;
        if (isset($function_key) &&$function_key != 0)$where_array['function_key'] = $function_key;

        $notice = Notice::where($where_array)
            ->join('admin_functions','admin_functions.id','=','notices.function_subkey')
            ->orderby('notices.id','desc')
            ->offset($pageNum)
            ->limit(20)
            ->get(['notices.id','notices.function_key','notices.relation_user_id','notices.content','notices.create_time','admin_functions.url']);

        foreach ($notice as $key){
            $key['create_time'] = $this->switchTime($key['create_time']);
            if ($this->inNoticeRedis($key['id'],$admin_id)){
                $key['islook'] = 0;
            }else{
                $key['islook'] = 1;
            }
        }
        return  $this->returnJson(self::SUCCESS,'成功',$notice);

    }

    /**
     *读通知
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function redNotice(Request  $request){
        $admin_id = $request->userId;

        $notice_id  = $request->get('notice_id');

        $flag = $this->delNoticeRedis($notice_id,$admin_id);
        if (!$flag){
            return $this->returnJson(self::ERROR,'失败');
        }
        return $this->returnJson(self::SUCCESS,'成功');
    }


    /**
     * 读所有通知
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function redAllNotice(Request  $request){
        $admin_id = $request->userId;

        if (!$this->delAllNoticeRedis($admin_id)){
            return $this->returnJson(self::SUCCESS,'已读');
        }
        return $this->returnJson(self::SUCCESS,'成功');
    }

    /**
     * get当前学期
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function  newSemester()
    {
        $data = Semester::where('id', '=', $this->getNewSemester())->first();
        $data['start_time'] =$this->switchTime($data['start_time'] );
        $data['end_time']=$this->switchTime($data['end_time'] );
       return $this->returnJson(self::SUCCESS,'成功 ',$data);
    }

    /**
     * 设置学期
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public  function  setSemester(Request $request){
        $semester_id = $request->input('semester_id');

        if (!SetSemester::where('id' ,'=', 1)->update(['semester_id' => $semester_id])) return $this->returnJson(self::ERROR,'数据库错误');

        return $this->returnJson(self::SUCCESS,'成功');
    }

    /**
     * 修改学期
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public  function  updateSemester(Request $request){
        $pram  = $request->only(['id','start_time','end_time','semester','week_length']);
        if(!empty($pram['start_time'])){
            $start_yeas = date('Y',$pram['start_time']);
            $end_yeas = date('Y',$pram['end_time']);
            if ($pram['semester'] == 0) {
                $sem = '一';
            }
            if ($pram['semester'] == 1) {
                $start_yeas = $start_yeas -1;
                $sem = '二';
            }
            $name = $start_yeas .'年～' . $end_yeas .'年第'. $sem . '学期';
            $pram['name'] = $name;
        }
        Semester::where('id','=',$pram['id'])->update($pram);

        return $this->returnJson(self::SUCCESS,'成功');
    }

    /**
     * get所有学期
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public  function  getSemester(Request $request){
        $semesterList = Semester::get();
        foreach ($semesterList as $key){
            $key['start_time'] =$this->switchTime($key['start_time'] );
            $key['end_time']=$this->switchTime($key['end_time'] );
        }
        return $this->returnJson(self::SUCCESS,'成功',$semesterList);
    }

    /**
     * 删除学期
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public  function  delSemester(Request $request){
        $semester_id = $request->input('semester_id');
        if (! Semester::where('id' ,'=', $semester_id)->delete()) return $this->returnJson(self::ERROR,'数据库错误');

        return $this->returnJson(self::SUCCESS,'成功');
    }

    /**
     * 添加学期
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function createSemesters(Request $request){
        $pram  = $request->only(['start_time','end_time','semester','week_length']);

        $start_yeas = date('Y',$pram['start_time']);
        $end_yeas = date('Y',$pram['end_time']);
        if ($pram['semester'] == 0) {
            $sem = '一';
        }
        if ($pram['semester'] == 1) {
            $start_yeas = $start_yeas -1;
            $sem = '二';
        }
        $name = $start_yeas .'年～' . $end_yeas .'年第'. $sem . '学期';

        $pram['name'] = $name;
        $pram['create_time'] = $pram['start_time'];

        if (!Semester::insert($pram)) return $this->returnJson(self::ERROR,'数据库错误');

        return $this->returnJson(self::SUCCESS,'成功');
    }

}
